package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @auther : 白月尘
 * @date : 10:30  2021/10/17
 */
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;


    public void saveUserInfo(UserInfo userInfo) {
        userInfo.setId(UserHolder.getUserId());
        userInfoApi.saveUserInfo(userInfo);
    }

    public void saveUserInfoById(MultipartFile headPhoto) throws IOException {
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = aipFaceTemplate.detect(upload);
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }
        UserInfo userInfo= new UserInfo();
        userInfo.setId(UserHolder.getUserId());
        userInfo.setAvatar(upload);
        userInfoApi.update(userInfo);
    }

    public UserInfoVo findById(Long userId) {
        if (userId==null){
            userId=UserHolder.getUserId();
        }
        UserInfo info = userInfoApi.findById(userId);
        UserInfoVo vo=new UserInfoVo();
        BeanUtils.copyProperties(info,vo);
        if(info.getAge() != null) {
            vo.setAge(info.getAge().toString());
        }
        return vo;
    }

}
